#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : config_spider
import scrapy
import json
import math
import time
import urllib.parse

from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class XinjiangKlmysPolicy(BaseTaxPolicySpider):
    name = 'xinjiang_klmys_policy'
    
    province = '新疆维吾尔自治区'
    city: str = "克拉玛依市"  # 取表格
    # county: str = ""  # 取表格
    park: str = ""  # 取表格
    custom_settings = {
        "DOWNLOAD_TIMEOUT": 60
    }

    def start_requests(self):
        for source, county, url in [
            ['克拉玛依市人民政府', "", "https://www.klmy.gov.cn/klmys/szfxzgfxwj/zfxxgk.shtml"],
            ['克拉玛依市人民政府', "", "https://www.klmy.gov.cn/klmys/szfbmxzgfxwj/zfxxgk.shtml"],
            ['克拉玛依市人民政府', "", "https://www.klmy.gov.cn/klmys/qczcwj/zfxxgk.shtml"],
            ['克拉玛依市人民政府', "", "http://www.klmyq.gov.cn/klmyq/qtzcwj/zfxxgk.shtml"],
            ['克拉玛依区人民政府', "克拉玛依区", "http://www.klmyq.gov.cn/klmyq/qzfgfxwj/zfxxgk.shtml"],
            ['克拉玛依区人民政府', "克拉玛依区", "http://www.klmyq.gov.cn/klmyq/qtzcwj/zfxxgk.shtml"],
            ['独山子区人民政府', "独山子区", "http://www.dsz.gov.cn/dsz/qzfxzgfxwj/zfxxgk.shtml"],
            ['独山子区人民政府', "独山子区", "http://www.dsz.gov.cn/dsz/qtzcwj/zfxxgk.shtml"],
            ['白碱滩区人民政府', "白碱滩区", "http://www.bjtq.gov.cn/bjtq/qzfxzgfxwj/zfxxgk.shtml"],
            ['白碱滩区人民政府', "白碱滩区", "http://www.bjtq.gov.cn/bjtq/qtzcwj/zfxxgk.shtml"],
            ['乌尔禾区人民政府', "乌尔禾区", "http://www.weh.gov.cn/weh/qzfgfxwj/zfxxgk.shtml"],
            ['乌尔禾区人民政府', "乌尔禾区", "http://www.weh.gov.cn/weh/qtzcwj/zfxxgk.shtml"],
        ]:
            item = {'source': source, 'county': county}
            yield scrapy.Request(url, callback=self.parse_content, meta={'item': item})

    def parse_content(self, response, **kwargs):
        meta = response.meta
        params = {
            "page": "1",
            "_pageSize": "15",
            "_isAgg": "true",
            "_isJson": "true",
            "_template": "index",
            "_rangeTimeGte": "",
            "_channelName": ""
        }
        channelId = response.xpath("//script").re_first(r'channelId\s*=\s*"(.*?)"')
        meta.update(**{"params": params, "url_api": f"/search/{channelId}?"})
        yield response.follow(f"/search/{channelId}?" + urllib.parse.urlencode(params), callback=self.parse_list,
                              meta=meta)

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        data = response.json()['data']
        elem_list = data['results']
        meta = response.meta
        for elem in elem_list:
            item = Item()
            item['source_url'] = elem['url']
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem['publishedTimeStr'].split(" ")[0]
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            # if '.htm' not in item['source_url'] and '.shtm' not in item['source_url']:
            #     continue
            # if 'list.shtml' in item['source_url']:
            #     continue
            print(response.url, item['source_url'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if response.meta.get("is_next") is not False:
            pages = math.ceil(int(data['total']) / 15)
            params = meta['params']
            print(response.url, f"page: {pages}")
            for page_num in range(2, int(pages) + 1):
                params['page'] = str(page_num)
                yield response.follow(meta['url_api'] + urllib.parse.urlencode(params), callback=self.parse_list, meta={'item': prev_item, 'is_next': False})

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get() or response.xpath("//*[@class='fbrq']/text()").get()
        item['content'] = response.xpath(""".""").get()
        # item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl xinjiang_klmys_policy".split())
